//
//  UserInfoViewController.m
//  JiuLe
//
//  Created by 黄鑫 on 16/8/30.
//  Copyright © 2016年 Fine. All rights reserved.
//

#import "UserInfoViewController.h"
#import "UserNameAlterViewController.h"
#import "AlertPasswordViewController.h"
#import "AlertPhoneViewController.h"
#import "ContactsViewController.h"
#import "BodyProfileViewController.h"
#import "AddressView.h"
#import "LoginViewController.h"
#import "UIImage+ImageEffects.h"
#import "PictureSelect.h"
#import "UIImageView+WebCache.h"
#import "EditRealNameViewController.h"
@interface UserInfoViewController ()<PictureSelectDelegate>
@property (weak, nonatomic) IBOutlet UILabel *labAddress;
@property (weak, nonatomic) IBOutlet UILabel *labPhone;
@property (weak, nonatomic) IBOutlet UILabel *labStart;
@property (weak, nonatomic) IBOutlet UILabel *labName;
@property (weak, nonatomic) IBOutlet UIImageView *imageUser;
@property (weak, nonatomic) IBOutlet UILabel *labNameReal;//真实姓名
@property (strong, nonatomic) PictureSelect *pictureSelect;
@property (strong, nonatomic) AddressView *addressView;
@property (strong, nonatomic) id responseObject;

@end

@implementation UserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"用户信息";
    [self showNavgationWithLeftItemWithTitle:@"我的"];
    [SVProgressHUD showWithStatus:@"获取用户信息.." maskType:SVProgressHUDMaskTypeClear];
    [self requestUserInfo];
    NSString *userID = [[NSUserDefaults standardUserDefaults] objectForKey:UserDataID];
    if (![userID isEqualToString:@""] && userID != nil) {
        self.labStart.text = @"退出登录";
    }else{
        self.labStart.text = @"登录";
    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    [self requestUserInfo];
}

#pragma mark 数据请求
- (void)requestUserInfo{
    [[BaseDataRequest alloc]getUserInfoWithBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            self.responseObject = responseObject;
            NSDictionary *dicResult = [responseObject objectForKey:@"result"];
            self.labPhone.text = [dicResult objectForKey:@"mobile"];
            self.labAddress.text = [dicResult objectForKey:@"location"];
            self.labName.text = [dicResult objectForKey:@"login_name"];
            self.labNameReal.text = [dicResult objectForKey:@"name"];
            [self.imageUser sd_setImageWithURL:[NSURL URLWithString:[dicResult objectForKey:@"head_url"]] placeholderImage:[UIImage imageNamed:@"icon_user-1"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
                if(image == nil){
                    self.imageUser.image = [UIImage imageNamed:@"icon_user-1"];
                }else{
                    self.imageUser.layer.borderWidth = 0;
                    self.imageUser.layer.cornerRadius = 23;
                    self.imageUser.layer.masksToBounds = YES;
                }
            }];
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"获取用户信息失败");
            }

        }
    }];
}

- (void)modifyShippingAddress:(NSString *)addressId{
    [SVProgressHUD showWithStatus:@"修改用户地区.." maskType:SVProgressHUDMaskTypeClear];
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:addressId forKey:@"location"];
    [dict setObject:[[NSUserDefaults standardUserDefaults] objectForKey:UserDataID] forKey:@"user_id"];
    [[BaseDataRequest alloc]modifyShippingAddress:dict withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        if ([status isEqualToString:@"0"]) {
            TIPSFORVIEW(@"修改用户地区成功");
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW(@"修改收货地址失败");
            }
            
        }
    }];
}

#pragma mark - UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
 
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            //修改用户头像
            if(_pictureSelect == nil){
                _pictureSelect=[[PictureSelect alloc]initWithView:self];
                _pictureSelect.delegate = self;
            }
            [_pictureSelect changeIcon];
        }else if (indexPath.row == 1) {
            //修改登录用户名
            UserNameAlterViewController *userInfo = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"UserNameAlterViewController"];
            userInfo.strName =  self.labName.text;
            [self.navigationController pushViewController:userInfo animated:YES];
        }else if (indexPath.row == 2){
            //修改真实姓名
            EditRealNameViewController *editName = [[UIStoryboard storyboardWithName:@"SCStoryboard" bundle:nil]instantiateViewControllerWithIdentifier:@"EditRealNameViewController"];
            editName.name = self.labNameReal.text;
            [self.navigationController pushViewController:editName animated:YES];
            
        }else if (indexPath.row == 3){
            //修改密码
            AlertPasswordViewController *alertPassword = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AlertPasswordViewController"];
            [self.navigationController pushViewController:alertPassword animated:YES];
        }else if (indexPath.row == 4){
            //用户手机
            AlertPhoneViewController *alertPhone = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"AlertPhoneViewController"];
            [self.navigationController pushViewController:alertPhone animated:YES];
        }else if (indexPath.row == 5){
            //紧急联系人
            ContactsViewController *contacts = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"ContactsViewController"];
            contacts.reponst = self.responseObject;
            [self.navigationController pushViewController:contacts animated:YES];
        }else if (indexPath.row == 7){
            //身体资料
            BodyProfileViewController *bodyProfile = [[UIStoryboard storyboardWithName:@"PersonalViewController" bundle:nil] instantiateViewControllerWithIdentifier:@"BodyProfileViewController"];
            bodyProfile.response = self.responseObject;
            [self.navigationController pushViewController:bodyProfile animated:YES];
        }else{
            //选择用户地址
            self.addressView = [[AddressView alloc] init:^(NSString *address ,NSString *addressId) {
                NSLog(@"%@  %@",address ,addressId);
                self.labAddress.text = address;
                [self modifyShippingAddress:addressId];
            }];
            self.addressView.frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            [self.view addSubview:self.addressView];
        }
    }else{
        if([self.labStart.text isEqualToString:@"登录"]){
            LoginViewController *login = getStoryOfControllerInstance(@"LoginViewController");
            BaseNavController *baseNav = [[BaseNavController alloc] initWithRootViewController:login];
            [UIApplication sharedApplication].delegate.window.rootViewController = baseNav;
        }else{
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:UserDataID];
            [[NSUserDefaults standardUserDefaults] setObject:@"" forKey:UserToken];
            self.labStart.text = @"登录";
            TIPSFORVIEW(@"退出登录成功");
            [self performSelector:@selector(back) withObject:nil afterDelay:1.1];
        }
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == 0 && indexPath.section == 0) {
        return 74;
    }else{
        return 50;
    }
}

#pragma mark - PictureSelectDelegate
-(void)iconChooseFinish:(UIImage*)img{
    self.imageUser.image = [img circleImage];
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
    [[BaseDataRequest alloc] uploadPicture:img withBlock:^(id responseObject, NSString *status, NSError *error) {
        [SVProgressHUD dismiss];
        [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
        if ([status isEqualToString:@"0"]) {
            TIPSFORVIEW(@"上传头像成功");
        }else{
            if (error != nil) {
                TIPSFORVIEW(@"请检测网络设置");
            }else{
                TIPSFORVIEW([responseObject objectForKey:@"message"]);
            }
        }
    }];
}

- (void)back{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
